import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_lottie/flutter_lottie.dart';
import 'package:recorder_wav/recorder_wav.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';

import 'action.dart';
import 'state.dart';

Widget buildView(
    PracticeVoiceState state, Dispatch dispatch, ViewService viewService) {
  List<DropdownMenuItem> typeItemList() {
    final List<DropdownMenuItem> items = List();
    GlobalState.articleTypes.forEach((key, value) {
      items.add(DropdownMenuItem(value: key, child: Text(value)));
    });
    return items;
  }

  List<DropdownMenuItem> gradeItemList() {
    final List<DropdownMenuItem> items = List();
    GlobalState.grades.forEach((key, value) {
      items.add(DropdownMenuItem(value: key, child: Text(value)));
    });
    items.removeRange(0, 2);
    return items;
  }

  var border = UnderlineInputBorder(
    borderSide: BorderSide(
      color: Colors.white,
    ),
  );

  LottieController controller1;

  void onViewCreated(LottieController controller) {
    controller1 = controller;

    // Listen for when the playback completes
    controller1.onPlayFinished.listen((bool animationFinished) {
      print("Playback complete. Was Animation Finished? " +
          animationFinished.toString());
    });
  }

  var recording = false;
  var isTitle = true;

  Widget bottomBox(StateSetter setState) {
    return Column(
      children: <Widget>[
        recording
            ? Container(
                width: 100,
                height: 100,
                child: LottieView.fromFile(
                  filePath: "assets/lotties/sound_visualizer.json",
                  autoPlay: true,
                  loop: true,
                  reverse: true,
                  onViewCreated: onViewCreated,
                ))
            : Container(height: 0.0, width: 0.0),
        Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: ExactAssetImage("assets/images/voice_bg3.png"),
                fit: BoxFit.cover,
              ),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                SizedBox(
                  width: 90,
                  child: Text(''),
                ),
                Column(mainAxisSize: MainAxisSize.min, children: <Widget>[
                  GestureDetector(
                    child: Container(
                      width: 80,
                      height: 56,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: ExactAssetImage("assets/images/voice_bg.png"),
                          fit: BoxFit.cover,
                        ),
                      ),
                      padding: EdgeInsets.all(16.0),
                      child: Image.asset("assets/images/voice.png"),
                    ),
                    onTapDown: (detail) {
                      setState(() {
                        recording = true;
                        isTitle = state.focusNodeTitle.hasFocus;
                      });
                      RecorderWav.startRecorder();
                    },
                    onTapUp: (detail) {
                      setState(() {
                        recording = false;
                      });
                      RecorderWav.StopRecorder();
                    },
                    onLongPressUp: () async {
                      setState(() {
                        recording = false;
                      });
                      var filePath = await RecorderWav.StopRecorder();
                      dispatch(PracticeVoiceActionCreator.focus(isTitle));
                      dispatch(PracticeVoiceActionCreator.onVoiceAi(filePath));
                    },
                  ),
                  Text(
                    '语音上传',
                    style: TextStyle(color: Colors.blue, fontSize: 12),
                  ),
                ]),
                GestureDetector(
                  child: Container(
                    width: 90,
                    decoration: const BoxDecoration(
                        gradient: LinearGradient(
                          colors: <Color>[
                            Colors.blue,
                            Colors.blue,
                          ],
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(80.0))),
                    padding: const EdgeInsets.all(10),
                    child: const Text('完成',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.white)),
                  ),
                  onTap: () => dispatch(PracticeVoiceActionCreator.onSubmit()),
                ),
              ],
            )),
      ],
    );
  }

  return new Scaffold(
      appBar: new AppBar(
          centerTitle: true,
          elevation: 2.0,
          title: new Text(
            "语音识别批改",
            style: TextStyle(color: Colors.black54, fontSize: 18),
          )),
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: ExactAssetImage("assets/images/voice_bg2.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: Card(
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(5.0),
            ),
            margin: EdgeInsets.all(10),
            child: Stack(
              children: <Widget>[
                SingleChildScrollView(
                    child: Column(
                  children: <Widget>[
                    Row(
                      mainAxisSize: MainAxisSize.max,
                      children: <Widget>[
                        SizedBox(width: 10),
                        Expanded(
                          flex: 1,
                          child: DropdownButton(
                            isExpanded: true,
                            hint: Text('文体类型'),
                            value: state.typeValue,
                            items: typeItemList(),
                            onChanged: (item) {
                              dispatch(
                                  PracticeVoiceActionCreator.selectType(item));
                            },
                          ),
                        ),
                        SizedBox(width: 10),
                        Expanded(
                          flex: 1,
                          child: DropdownButton(
                            isExpanded: true,
                            hint: Text('年级'),
                            value: state.gradeValue,
                            items: gradeItemList(),
                            onChanged: (item) {
                              dispatch(
                                  PracticeVoiceActionCreator.selectGrade(item));
                            },
                          ),
                        ),
                        SizedBox(width: 10),
                      ],
                    ),
                    TextField(
                      maxLines: 1,
                      autofocus: true,
                      controller: state.titleEditController,
                      focusNode: state.focusNodeTitle,
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(8),
                        hintText: '请输入作文标题',
                        hintStyle: TextStyle(color: Colors.blue),
                        enabledBorder: border,
                        focusedBorder: border,
                      ),
                    ),
                    SizedBox(height: 10),
                    Divider(height: 1),
                    SizedBox(height: 10),
                    TextField(
                      maxLines: null,
                      minLines: 12,
                      controller: state.contentEditController,
                      focusNode: state.focusNodeContent,
                      decoration: InputDecoration(
                        contentPadding: EdgeInsets.all(8),
                        hintText: '请输入作文内容',
                        hintStyle: TextStyle(color: Colors.blue),
                        enabledBorder: border,
                        focusedBorder: border,
                      ),
                    ),
                    SizedBox(height: 70),
                  ],
                )),
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child:
                      StatefulBuilder(builder: (context, StateSetter setState) {
                    return SizedBox(
                        height: recording ? 180 : 80,
                        child: bottomBox(setState));
                  }),
                )
              ],
            )),
      ));
}
